package com.suse.blog.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.util.UUID;

@Slf4j
public class SecurityUtils {
    /**
     * 加密
     * @param password
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String encrypt(String password)  {
        String salt = UUID.randomUUID().toString().replace("-","");
        //md5(salt+password)
        String secretString = null;
        try {
            secretString = DigestUtils.md5DigestAsHex((salt+password).getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        //数据库存储   盐值+密文
        return salt + secretString;
    }
    /**
     * 解密
     */
    public static Boolean verify(String password, String finalPassword)  {
        if(finalPassword == null && finalPassword.length() != 64) {
            log.info("密码格式不正确");
            return false;
        }
        String salt = finalPassword.substring(0, 32);
        //md5(salt+password)
        String secretString = null;
        try {
            secretString = DigestUtils.md5DigestAsHex((salt+password).getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            log.error("getBytes 异常， e:",e);
            throw new RuntimeException(e);
        }
        //数据库存储   盐值+密文
        return (salt + secretString).equals(finalPassword);

    }
}
